import { stationApi, StationDTO } from '@/services/api/stationApi';
import StringUtils from '@/utils/StringUtils';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { TouchableOpacity, View, Text, Alert } from 'react-native';
import {
  FlatList,
  RectButton,
  RefreshControl,
} from 'react-native-gesture-handler';
import Swipeable, {
  SwipeableMethods,
} from 'react-native-gesture-handler/ReanimatedSwipeable';
import FastImage from 'react-native-fast-image';
import { Icon, Tag, useAppTheme } from 'tsun-smart-ui';
import Reanimated, {
  SharedValue,
  useAnimatedStyle,
} from 'react-native-reanimated';
import ListEmptyLoadingComponent from '@/components/ListEmptyLoadingComponent';
import ArrayUtils from '@/utils/ArrayUtils.ts';
import NoStationIcon from '@/assets/icon/no-station.svg';

const stationStatusMap = {
  normal: {
    label: 'job.status.Normal',
    color: 'success',
  },
  offline: {
    label: 'monitor.tab.title.offline',
    color: 'disabled',
  },
  pending: {
    label: 'monitor.tab.title.installing',
    color: 'warning',
  },
  installed: {
    label: 'station.installed',
    color: 'info',
  },
} as const;
type StationStatus = keyof typeof stationStatusMap;

const OwnerStationList: React.FC = (props) => {
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const [stationList, setStationList] = useState<StationDTO[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { t } = useTranslation();
  const appTheme = useAppTheme();
  const pageRef = useRef(1);
  const noMoreDataRef = useRef(false);
  const swipeableRef = useRef<SwipeableMethods[]>([]);
  const [loadedDataOnce, setLoadedDataOnce] = useState(false);

  useEffect(() => {
    reloadStations();
  }, []);

  const reloadStations = useCallback(() => {
    loadStationsAtPage(1);
  }, []);

  const loadMoreStations = useCallback(() => {
    if (noMoreDataRef.current || ArrayUtils.isEmpty(stationList) || loading) {
      return;
    }
    loadStationsAtPage(pageRef.current + 1);
  }, [stationList, loading]);

  const loadStationsAtPage = useCallback(
    (page: number) => {
      setLoading(true);
      const pageSize = 10;
      stationApi
        .getUserStations({ pageNum: page, pageSize: pageSize })
        .then((res) => {
          if (res.data.records) {
            setLoadedDataOnce(true);
            if (page <= 1) {
              noMoreDataRef.current = res.data.records.length >= res.data.total;
              setStationList(res.data.records);
            } else {
              const newStations = [...stationList, ...res.data.records];
              noMoreDataRef.current =
                res.data.records.length >= newStations.length;
              pageRef.current = page;
              setStationList(newStations);
            }
          }
          setLoading(false);
        })
        .catch(() => {
          setLoading(false);
        });
    },
    [stationList, loading]
  );

  const renderRightAction = useCallback(
    (
      prog: SharedValue<number>,
      drag: SharedValue<number>,
      dragMethods: any,
      onPress: () => void
    ) => {
      const styleAnimation = useAnimatedStyle(() => {
        return {
          // transform: [{ translateX: drag.value + 64 }],
        };
      });

      return (
        <Reanimated.View style={styleAnimation}>
          <TouchableOpacity
            className="bg-red-500 rounded-xl w-16 flex-1 justify-center"
            onPress={onPress}
            activeOpacity={0.9}
          >
            <Text className="text-center text-white text-[15px]">
              {t('pb.delete')}
            </Text>
          </TouchableOpacity>
        </Reanimated.View>
      );
    },
    []
  );

  const renderItem = useCallback(({ item }: { item: StationDTO }) => {
    const timezoneText =
      'tz.' + item.timezone.replaceAll('/', '.').toLowerCase();
    const timezone = t(timezoneText);

    const onDelete = () => {
      if (item.id) {
        Alert.alert(
          t('sys.app.confirm.delete'),
          undefined,
          [
            {
              text: t('user.logOutCancel'),
              onPress: () => {},
            },
            {
              text: t('common.confirmButtonText'),
              onPress: () => {
                stationApi.deleteStation(item.id!).then(() => {
                  setStationList((prev) =>
                    prev.filter((i) => i.id !== item.id)
                  );
                  reloadStations();
                });
              },
            },
          ],
          { cancelable: true }
        );
      }
    };
    const stationStatus = item.stationStatus ?? 'normal';
    const stationStatusInfo =
      stationStatusMap[stationStatus] ?? stationStatusMap['normal'];
    const noImage = item.coverImage === undefined || item.coverImage === null;
    const imageSource = noImage
      ? require('@/assets/imgs/station-placeholder.png')
      : { uri: StringUtils.toImageUri(item.coverImage) };
    return (
      <Swipeable
        renderRightActions={(prog, drag, dragMethods) =>
          renderRightAction(prog, drag, dragMethods, onDelete)
        }
        rightThreshold={40}
        overshootRight={false}
        ref={(ref) => {
          if (ref) {
            swipeableRef.current.push(ref);
          }
        }}
        // onSwipeableOpenStartDrag={() => closeSwipeables()}
        // onSwipeableWillOpen={() => closeSwipeables()}
      >
        <TouchableOpacity
          className="p-5 items-stretch bg-fill2 rounded-xl gap-4"
          activeOpacity={0.9}
          onPress={() =>
            navigation.navigate('CreatePowerStation', { station: item })
          }
        >
          <View className="gap-3 flex-row">
            <FastImage
              source={imageSource}
              defaultSource={require('@/assets/imgs/station-placeholder.png')}
              resizeMode="cover"
              className="w-16 h-16 rounded-xl bg-black/10"
            />
            <View className="stretch flex-1 gap-1" key={'电站封面右侧字段'}>
              <View
                className="flex-row items-center justify-between"
                key={'名称和标签'}
              >
                <Text className="font-medium text-text1 text-[16px] shrink">
                  {item.stationName}
                </Text>
                <Tag type={stationStatusInfo.color}>
                  {t(stationStatusInfo.label)}
                </Tag>
              </View>
              <Text className="text-text3 text-[12px]">
                {t('monitor.statType', { defaultValue: '电站类型' })}：
                {t(item.stationType)}
              </Text>
              <Text className="text-text3 text-[12px]">
                {t('sys.app.time.zone', { defaultValue: '时区' })}：{timezone}
              </Text>
            </View>
          </View>
          <View className="flex-row gap-2 items-start">
            <Icon
              name="position"
              size={14}
              color={appTheme.colors?.neutral?.secondaryTitle}
            />
            <Text className="text-text3 text-[12px] leading-3 flex-1 shrink">
              {item.address}
              {item.detailAddress}
            </Text>
          </View>
        </TouchableOpacity>
      </Swipeable>
    );
  }, []);

  return (
    <>
      <FlatList
        className="flex-1"
        contentContainerClassName="px-3 py-3"
        data={stationList}
        renderItem={renderItem}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={reloadStations} />
        }
        ItemSeparatorComponent={ItemSeparator}
        ListEmptyComponent={() => <ListEmpty loadDataOnce={loadedDataOnce} />}
        keyExtractor={(item, index) => item.id?.toString() ?? item.stationName}
      />
    </>
  );
};

export default React.memo(OwnerStationList);

const ItemSeparator: React.FC = React.memo((props) => {
  return <View className="h-4" />;
});

const ListEmpty = React.memo((props: { loadDataOnce: boolean }) => {
  const { t } = useTranslation();
  if (props.loadDataOnce) {
    return (
      <View>
        <NoStationIcon
          width={45}
          height={45}
          style={{
            marginTop: 180,
            alignSelf: 'center',
            marginBottom: 8,
          }}
        />
        <Text className="text-text4 self-center mb-4">
          {t('sys.app.no.station', { defaultValue: '暂无电站' })}
        </Text>
      </View>
    );
  }
  return <ListEmptyLoadingComponent />;
});

type LabelAndValueProps = {
  label: string;
  value: string | null | undefined;
};

const LabelAndValue: React.FC<LabelAndValueProps> = React.memo((props) => {
  return (
    <View className="gap-y-[2px] flex-1">
      <Text className="text-text4 text-[12px]">{props.label}</Text>
      <Text className="text-text1 text-[14px] font-medium">
        {props.value ?? '- -'}
      </Text>
    </View>
  );
});
